package com.application.api;

import com.application.model.Order;
import com.application.pay.AbstractPayNotify;
import com.application.pay.WxPayNotify;
import com.github.wxpay.sdk.WXPayUtil;
import com.jfinal.aop.Clear;
import com.platform.annotation.Controller;
import com.platform.interceptor.AuthInterceptor;
import com.platform.interceptor.LoginInterceptor;
import com.platform.interceptor.ParamPkgInterceptor;
import com.platform.interceptor.XSSInterceptor;
import com.platform.mvc.base.BaseController;

import javax.servlet.ServletInputStream;
import java.util.Map;

/**
 * Created by Administrator on 2017/12/27 0027.
 */
@Controller("/api/pay/notify/wx")
@Clear({AuthInterceptor.class, LoginInterceptor.class, ParamPkgInterceptor.class, XSSInterceptor.class})
public class PayNotifyWxController extends BaseController {

    String s = "<xml> \n" +
            "\n" +
            "  <return_code><![CDATA[SUCCESS]]></return_code>\n" +
            "  <return_msg><![CDATA[OK]]></return_msg>\n" +
            "</xml> \n";

    /*
        * 微信回调接口，第三方支付平台回调订单状态修改订单状态
        */
    public void index() throws Exception {
        String msg = null;
        ServletInputStream instream = getRequest().getInputStream();
        StringBuffer sb = new StringBuffer();
        int len = -1;
        byte[] buffer = new byte[1024];

        while((len = instream.read(buffer)) != -1){
            sb.append(new String(buffer,0,len));
        }
        instream.close();

        Map<String, String> map = WXPayUtil.xmlToMap(sb.toString());
        System.err.println("####################### wxpay notify content :#######");
        System.err.println(map);

        if("SUCCESS".equals(map.get("return_code")) && "SUCCESS".equals(map.get("result_code"))){

            if(map.containsKey("refund_id")){
                renderText(s);
                System.err.println("################## wx refund notify ############");
            } else {
                String fee = map.get("total_fee");
                AbstractPayNotify notify = new WxPayNotify(map.get("time_end"), WxPayNotify.getFormatMoney(fee),
                        Order.PAY_WX, map.get("appid"), map.get("out_trade_no"));
                notify.run();
            }

        } else {
            msg = "订单支付失败（orders pay error）:" + map.get("return_msg");
        }
        System.err.println(msg);

        renderText(s);
    }



}
